package com.xuan.utils.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * IP工具
 */
public class IpUtil {

    /**
     * 获取机器的公网ip
     *
     * @return 机器的公网ip
     */
    public static String getPublicIp() {

        try {
            URL url = new URL("https://httpbin.org/ip");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            in.close();
            connection.disconnect();

            // 解析JSON以获取IP地址，实际响应可能是JSON或其他格式，需要根据实际情况解析
            JSONObject jsonObj = JSON.parseObject(content.toString());
            return jsonObj.getString("origin");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "127.0.0.1"; // 默认返回内网ip

    }


}
